package com.zat.mes.andrmes.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import com.zat.mes.andrmes.R;
import com.zat.mes.andrmes.dofun.main.MainActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;


public class UpdateManager {
    private Context context;
    /**
     * 进度百分比
     */
    private String savePath = "";
    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;
    private static final int DOWN_ERROR = 3;
    private int progress = 0;

    private Thread downLoadThread;

    private boolean interruptFlag = false;

    private String fileUrl;

    private TextView tvProgress;
    private ProgressBar progressBar;
    private AlertDialog downDialog;
    private String saveFileName;
    private int installRequestCode = 201;

    public UpdateManager(Context context, String url, int installRequestCode) {
        this.context = context;
        this.installRequestCode = installRequestCode;
//        savePath = context.getFilesDir().getPath();
        savePath = context.getExternalCacheDir().getPath();
        fileUrl = url;
        saveFileName = "mes-release.apk";
        /**
         * 提示下载
         */
        if (!TextUtils.isEmpty(fileUrl)) {
//            showNoticeDialog();
            showDownLoad();
            downLoadAPK();
        }
    }

    private void showDownLoad() {
        View downLoadView = LayoutInflater.from(context).inflate(R.layout.dialog_download_layout, null);
        downDialog = new AlertDialog.Builder(context)
                .setView(downLoadView)
                .show();
        tvProgress = downLoadView.findViewById(R.id.tvPress);
        progressBar = downLoadView.findViewById(R.id.progressDownDialog);


    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWN_UPDATE:
                    tvProgress.setText(progress + "/100");
                    progressBar.setProgress(progress);
                    break;
                case DOWN_OVER:
                    installApkO();
                    tvProgress.setText("100/100");
                    if (downDialog != null) {
                        downDialog.dismiss();
                    }
                    break;
                case DOWN_ERROR:
                    Toast.makeText(context, "下载失败", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };


    private void downLoadAPK() {
        downLoadThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //如果5.0以下替换
                    fileUrl = HttpsKitUtils.replaceHttpsUrl(fileUrl);
                    URL url = new URL(fileUrl);
                    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String string, SSLSession ssls) {
                            return true;
                        }
                    });
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File file2 = new File(savePath, saveFileName);
                    if (file2.exists())
                        file2.delete();
                    //保存新文件.
                    FileOutputStream fos = new FileOutputStream(file2);

                    int count = 0;
                    byte buf[] = new byte[1024];

                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        //更新进度
                        mHandler.sendEmptyMessage(DOWN_UPDATE);
                        if (numread <= 0) {
                            //下载完成通知安装
                            mHandler.sendEmptyMessage(DOWN_OVER);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!interruptFlag);//点击取消就停止下载.

                    fos.close();
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(DOWN_ERROR);
                }
            }
        });
        downLoadThread.start();
    }


    /**
     * 兼容8.0安装位置来源的权限
     */
    private void installApkO() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //是否有安装位置来源的权限
            boolean haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
            if (haveInstallPermission) {
                Log.i("down", "8.0手机已经拥有安装未知来源应用的权限，直接安装！");
                installApk();
            } else {
                Uri packageUri = Uri.parse("package:" + context.getPackageName());
                Intent settingIntent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                if (context instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) context;
                    try {
                        mainActivity.startActivityForResult(settingIntent, installRequestCode);
                    } catch (Exception e) {
                        Log.e("activity", e.toString());
                    }
                }
            }
        } else {
            installApk();
        }
    }


    public void resultInstall() {
        installApkO();
    }

    /**
     * 安装apk
     * `
     *
     * @param
     */
    private void installApk() {
        File mFile = new File(savePath, saveFileName);
        if (!mFile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri apkUri = FileProvider.getUriForFile(context, "com.ntl.mes.andrmes.fileProvider",
                    mFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(mFile), "application/vnd" +
                    ".android.package-archive");
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            Log.e("activity", e.toString());
        }
    }


}
